package com.bdqn.util;

import com.chapter02.TestConnection5;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * jdbc的帮助类
 */
public class JDBCUtils {
    private static String driverClazz;
    private static String url;
    private static String userName;
    private static String userPwd;

    static {
        InputStream inputStream = TestConnection5.class
                .getClassLoader().getResourceAsStream("jdbc.properties");

        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driverClazz = properties.getProperty("driverClazz");
        url = properties.getProperty("url");
        userName = properties.getProperty("userName");
        userPwd = properties.getProperty("userPwd");

        // todo 通过反射的方式，创建一个驱动
        try {
            Class.forName(driverClazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    private static ComboPooledDataSource cpds = null;

    static {
//        cpds = new ComboPooledDataSource();
//        try {
//            cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
//        } catch (PropertyVetoException e) {
//            e.printStackTrace();
//        }
//        cpds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/myschool?rewriteBatchedStatements=true");
//        cpds.setUser("root");
//        cpds.setPassword("root");
//
//        cpds.setMinPoolSize(5);
//        cpds.setAcquireIncrement(5);
//        cpds.setMaxPoolSize(20);
    }


   private static BasicDataSource dataSource;
    static {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/myschool?rewriteBatchedStatements=true");
        dataSource.setPassword("root");
        dataSource.setUsername("root");

        dataSource.setMaxActive(10);
        dataSource.setInitialSize(3);
    }



    /**
     * 把获取connection对象封装起来
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {

        return dataSource.getConnection();

        // return cpds.getConnection();


        // return DriverManager.getConnection(url, userName, userPwd);
    }

    /**
     * 通用的增删改操作
     *
     * @param sql
     * @param objs
     * @return
     */
    public static int update(String sql, Object... objs) {
        int result = 0;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);
            if (objs.length > 0) { // 参数的个数有
                for (int i = 0; i < objs.length; i++) {
                    preparedStatement.setObject(i + 1, objs[i]);
                }
            }
            result = preparedStatement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResource(connection, preparedStatement, null);
        }
        return result;
    }

    /**
     * 带事务的更新操作：保证所有的操作使用同一个连接
     *
     * @param sql
     * @param objs
     * @return
     */
    public static int updateTx(Connection connection, String sql, Object... objs) {
        int result = 0;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (objs.length > 0) { // 参数的个数有
                for (int i = 0; i < objs.length; i++) {
                    preparedStatement.setObject(i + 1, objs[i]);
                }
            }
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResource(connection, preparedStatement, null);
        }
        return result;
    }

    /**
     * 通用的查询操作
     *
     * @param clazz
     * @param sql
     * @param objs
     * @param <T>
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws NoSuchFieldException
     */
    public static <T> List<T> query(Class<T> clazz, String sql, Object... objs) {
        List<T> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData rsmd = resultSet.getMetaData();
            int columnCount = rsmd.getColumnCount();

            while (resultSet.next()) {
                // 通过反射的方式创建了一个grade对象
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    // 拿到每一列的值
                    Object objValue = resultSet.getObject(i + 1);
                    // 可以拿到列的名称
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    // 拿到一个字段
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, objValue);
                }
                list.add(t);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            closeResource(connection, preparedStatement, resultSet);
        }
        return list;
    }

    /**
     * 通用的关闭资源的操作
     *
     * @param connection
     * @param preparedStatement
     * @param rs
     */
    public static void closeResource(Connection connection, Statement preparedStatement, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
